#!/usr/bin/python3
# -*- coding: utf-8 -*-
# ======================================#
# @Author   : duanqizhong
# @time     : 2022-8-7 0:06
# @file     : core
# @Software : PyCharm
# ======================================#
import socket

from base.func import ssh_client
from monitor.settings import CONNECT_TIMEOUT


class Monitor:
    def port(self, ip, port):
        infos = {
            "status": True,
            "msg": "ok"
        }
        s = socket.socket()
        s.settimeout(3)
        host = (ip, port)
        try:
            if int(port) > 65535 or int(port) < 0:
                infos["status"] = False
                infos["msg"] = f"port={port} was invalid"
            else:
                s.settimeout(CONNECT_TIMEOUT)
                s.connect(host)
        except socket.error as e:
            infos["status"] = False
            infos["msg"] = str(e)
        except Exception as ex:
            infos["status"] = False
            infos["msg"] = str(ex)
        # print(infos)
        return infos

    def cpu(self, ip, key, limit=90):
        infos = {
            "status": True,
            "idle": 0,
            "msg": "ok"
        }
        cmd = """vmstat 2 3 | tail -n 1 | awk '{print $15}'"""
        cpu_info = ssh_client(ip, cmd, key)
        if cpu_info["status"]:
            if cpu_info["stdout"]:
                cpu_idle = int(cpu_info["stdout"])
                if cpu_idle < 100 - limit:
                    infos["status"] = False
                    infos["idle"] = cpu_idle
                    infos["msg"] = f"cpu idle:{cpu_idle} was lower than limit={limit}"
        else:
            infos["status"] = False
            infos["msg"] = cpu_info["msg"]
        return infos

    def disk_free(self, ip, key, limit=90):
        infos = {
            "status": True,
            "free": 0,
            "msg": "ok"
        }
        cmd = """df -lh |grep 'dev' |awk '{print $5}' | awk -F"%" '{print $1}'"""
        disk_info = ssh_client(ip, cmd, key)
        if disk_info["status"]:
            if disk_info["stdout"]:
                disk_value_list = disk_info["stdout"].split('\n')
                max_use = 0
                for disk_value in disk_value_list:
                    if len(disk_value) == 0:
                        continue
                    disk_use = int(disk_value)

                    if disk_use > limit:
                        if disk_use > max_use:
                            max_use = disk_use
                        infos["status"] = False
                infos["free"] = max_use
        else:
            infos["status"] = False
            infos["msg"] = disk_info["msg"]

        return infos

    def memory(self, ip, key, env="stage", limit=1024):
        infos = {
            "status": True,
            "free": 0,
            "msg": "ok"
        }
        cmd = """free -m | grep - | awk '{print $4}'"""
        memory_info = ssh_client(ip, cmd, key)
        if memory_info["status"]:
            if memory_info["stdout"]:
                mem_value = int(memory_info["stdout"])
                if mem_value < limit:
                    infos["status"] = False
                    infos["free"] = memory_info
                    infos["msg"] = f"memory free space was lower than limit={limit}mb"
        else:
            infos["status"] = False
            infos["msg"] = memory_info["msg"]

        return infos
